package top.forgirl.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Date;

public class JwtUtil {
    private static Algorithm algorithm = Algorithm.HMAC256("top.forgirl");

    public static String generateJwt(String principal) {
        return JWT.create()
                .withIssuer("top.forgirl")
                .withIssuedAt(new Date())
                .withExpiresAt(returnExpireDate(7))
                .sign(algorithm);
    }

    public static DecodedJWT verifyJwt(String jwt) {
        if (jwt == null) {
            return null;
        }

        JWTVerifier jwtVerifier = JWT.require(algorithm)
                .withIssuer("top.forgirl")
                .build();

        return jwtVerifier.verify(jwt);
    }

    private static Date returnExpireDate(int day) {
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE, day);
        return instance.getTime();
    }
}
